<?php

namespace App\Kuafu\Base\Model\Traits;

use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Pay\Model\PayStreamModel;

/**
 * 支付分表
 */
trait KfPayStreamSplit
{
    /*
     * 设置表后缀
     */
    public static function suffix(?int $shopId = null, int $sysType = PayStreamModel::SYS_TYPE_RMS_MEAL): self
    {
        if (is_int($shopId) && $shopId < 0) {
            $shopId = 0;
        }

        if (!in_array($sysType, PayStreamModel::SYS_TYPE_PAY_IN_APP)) {
            $shopId = null;
        }

        // 非堂食业务-查老库
        if ($shopId === null) {
            return (new static)->setSplitShopId(null)->setSysType($sysType);
//                ->setConnection('mysql');
        }

        // 查分库
        return (new static)->setSplitShopId($shopId)->setSysType($sysType);
//                           ->setConnection(OrderDb::orderDbConnection($shopId, OrderDb::DB_TYPE_PAY, $sysType));
    }

    // 重写表名
    public function getTable(): string
    {
        $tableName = parent::getTable();
        if (!isset(self::$splitShopId)) {
            return $tableName;
        }

        // 已经有后缀了，不反复加了
        if (preg_match("/^[a-zA-z_]*_\d*$/", $tableName)) {
            return $tableName;
        }

        $suffix = self::$splitShopId !== null ? $this->getSuffixByShopId() : '';
        return $tableName . $suffix;
    }

    public function getConnectionName(): string
    {
        if (!isset(self::$splitShopId) || self::$splitShopId === null) {
            return 'mysql';
        }

        return OrderDb::orderDbConnection(self::$splitShopId, OrderDb::DB_TYPE_PAY, self::$sysType);
    }

    // 获取Model里配置的初始表名
    public function getBaseTable(): string
    {
        return parent::getTable();
    }
}
